package com.mind.core.db;

import org.apache.log4j.Logger;

import com.bugull.mongo.MongoConnection;
import com.mind.db.DAOConstants.DBType;
import com.mind.db.DBConfig;
import com.mind.db.IConnection;
import com.mind.db.ServerAddr;
import com.mind.db.async.AsyncUpdateManager;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.ReadPreference;

/**
 * servive for getting dao action 2012-3-23@author yangshaobo
 */
public class DBService {
	protected static Logger logger = Logger.getLogger(DBService.class);
	private static IConnection connection;
	private static IConnection logConnection;
	private static DBService dbService=new DBService();
	public static DBService getInstance(){
		return dbService;
	}
	
	public  void start(){
		connect();
		connectLog();
		AsyncUpdateManager.getInstance().start();
	}
	
	private  boolean connect() {
		DBConfig config=DBConfig.getInstance();
		DBType type=	config.getDb_type();
		switch (type) {
		case MONGODB:
			connection = MongoConnection.getInstance();
			MongoConnection conn = (MongoConnection) connection;
			/** 数据库配置 */
			ServerAddr serverAddr = config.getDb_addr();
			conn.setHost(serverAddr.getIp());
			conn.setPort(serverAddr.getPort());
			conn.setUsername(config.getDb_username());
			conn.setPassword(config.getDb_password());
			conn.setDatabase(config.getDb_name());
			conn.setReadPreference(ReadPreference.secondaryPreferred());// 设置从服务器可读
			Builder builder=new Builder();
			builder.connectionsPerHost(config.getDb_max_conn());
			conn.setOptions(builder.build());
			/** 数据库连接 */
			boolean isOk = conn.connect();
			if (!isOk) {
				return false;
			}
			break;
		}
		return true;
	}
	private  boolean connectLog() {
		DBConfig config=DBConfig.getInstance();
		DBType type=	config.getLog_db_type();
		switch (type) {
		case MONGODB:
			connection = MongoConnection.getInstance();
			MongoConnection conn = (MongoConnection) connection;
			/** 数据库配置 */
			ServerAddr serverAddr = config.getLog_db_addr();
			conn.setHost(serverAddr.getIp());
			conn.setPort(serverAddr.getPort());
			conn.setUsername(config.getLog_db_username());
			conn.setPassword(config.getLog_db_password());
			conn.setDatabase(config.getDb_name());
			conn.setReadPreference(ReadPreference.secondaryPreferred());// 设置从服务器可读
			conn.setReadPreference(ReadPreference.secondaryPreferred());// 设置从服务器可读
			Builder builder=new Builder();
			builder.connectionsPerHost(config.getLog_db_max_conn());
			conn.setOptions(builder.build());
			/** 数据库连接 */
			boolean isOk = conn.connect();
			if (!isOk) {
				return false;
			}
			break;
		}
		return true;
	}
	public  boolean stop() {
		if(connection!=null){
			connection.close();
		}
		if(logConnection!=null){
			logConnection.close();
		}
		return true;
	}

}
